import json
import time

from manager.api.device import DeviceApi
from manager.tool import TestTool as testTool


class EventMessagePushTool:
    """
    事件消息推送工具
    """

    @staticmethod
    def report_360_api(dateKey, dateValue):
        """
        360事件消息推送接口
        :param dateKey: 事件消息推送时间
        :param dateValue: 事件消息推送时间
        :return:
        """
        api = DeviceApi()
        r = api.api_eventmessage_deviceeventnotify_360(dateKey, dateValue)

        # 打印输出结果
        testTool.printAndLogResponse(r)

    @staticmethod
    def get_notity_list(filepath) -> list:
        """
        获取360事件消息推送文件中的内容
        :param filepath: 事件消息推送文件路径
        :return:请求数据
        """
        fs = open(filepath, 'r', encoding='utf-8')
        content = fs.read()
        fs.close()
        notity_list = []
        start_key = '360订阅消息异步数据'
        end_key = "| \'\'"
        while content.find(start_key) != -1:
            start_index = content.find(start_key) + len(start_key)
            end_index = content.find(end_key)
            json_str = content[start_index + 1:end_index]
            notity_list.append(json_str)
            content = content[end_index + len(end_key):]

        return notity_list

    @staticmethod
    def start(file_path):
        """
        启动事件消息推送
        :param file_path: 事件消息推送文件路径
        :return:
        """
        notitys = EventMessagePushTool.get_notity_list(file_path)
        data_key = ["msg", "sign"]
        for n in notitys:
            notity_json = json.loads(n)
            data_value = [notity_json.get(data_key[0]), notity_json.get(data_key[1])]
            EventMessagePushTool.report_360_api(data_key, data_value)
            time.sleep(1)


if __name__ == '__main__':
    _path = r"D://notify.txt"
    a = EventMessagePushTool()
    a.start(_path)
